<template>
    <div class="platform-mgt">
        <!-- 材料信息页面 -->
        <div class="mgt-top">
            <!-- 材料基础信息 -->
            <div class="info">
                <div class="header-img">
                    <image-preview :src="userInfoList.profilePictureImg" :width="108" :height="108"
                        style="border-radius:50%;"></image-preview>
                </div>
                <div class="material-info">
                    <div class="material-name">{{ userInfoList.materialSupplierName }}</div>
                    <div class="address">
                        <!-- <i class="iconfont icon-trophy"></i> -->
                        {{ userInfoList.contactInformation }} | {{ userInfoList.address }}
                    </div>
                </div>
            </div>
            <!-- 材料信息统计 -->
            <div class="work">
                <div class="count-box">
                    <div class="title">入驻时间</div>
                    <div class="num title">{{ parseTime(userInfoList.createTime, "{y}-{m}-{d}") }}</div>
                </div>
                <div class="count-box">
                    <div class="title">材料数量</div>
                    <div class="num title">{{ materialTotal || 0 }}</div>
                </div>
            </div>
        </div>
        <!-- 材料管理部分 -->
        <div class="mgt-bottom">
            <div class="mgt-bottom-sort">
                <el-input v-model="queryParams.materialName" placeholder="搜索材料名称" size="small" clearable
                    @keyup.enter="handleQuery" @clear="clear" style="width: 200px"></el-input>
                <el-dropdown trigger="click" @command="handleCommand">
                    <span><i class="iconfont icon-sort"></i>调整排序</span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="materialId&desc">
                                <div :class="adjustSort === 'materialId&desc' ? 'adjust-sort' : ''">按创建时间降序</div>
                                <el-icon v-show="adjustSort === 'materialId&desc'" color="#F28472" class="no-inherit"
                                    style="margin-left:10px;"><Select /></el-icon>
                            </el-dropdown-item>
                            <el-dropdown-item command="materialId&asc">
                                <div :class="adjustSort === 'materialId&asc' ? 'adjust-sort' : ''">按创建时间升序</div>
                                <el-icon v-show="adjustSort === 'materialId&asc'" color="#F28472" class="no-inherit"
                                    style="margin-left:10px;"><Select /></el-icon>
                            </el-dropdown-item>
                            <el-dropdown-item command="likes&desc">
                                <div :class="adjustSort === 'likes&desc' ? 'adjust-sort' : ''">按点赞数降序</div>
                                <el-icon v-show="adjustSort === 'likes&desc'" color="#F28472" class="no-inherit"
                                    style="margin-left:10px;"><Select /></el-icon>
                            </el-dropdown-item>
                            <el-dropdown-item command="likes&asc">
                                <div :class="adjustSort === 'likes&asc' ? 'adjust-sort' : ''">按点赞数升序</div>
                                <el-icon v-show="adjustSort === 'likes&asc'" color="#F28472" class="no-inherit"
                                    style="margin-left:10px;"><Select /></el-icon>
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>
            <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleTabClick">
                <el-tab-pane v-for="v in tabHeaderList" :label="v.label" :name="v.name">
                    <div v-if="total > 0">
                        <div class="tab-box" v-for="value in listData" :key="v.id" v-loading="loading">
                            <div class="tab-content">
                                <div class="tab-img">
                                    <image-preview :src="value.coverImageUrl" :width="175" :height="160"
                                        style="border-radius:8px;"></image-preview>
                                </div>
                                <div class="tab-info">
                                    <div class="tab-top-info">
                                        <div class="title" style="margin-bottom:8px;"><span class="set-top"
                                                v-show="value.isTop">置顶</span>{{ value.materialName }}</div>
                                        <div class="tag-list-des">{{ value.materialBriefly }}</div>
                                        <div class="base-list">
                                            <div class="date">{{ value.updateTime }}上传</div>
                                            <div class="view"><i class="iconfont icon-eye"></i>{{ value.visits }}</div>
                                            <div class="thumbs"><i class="iconfont icon-thumb"></i>{{ value.likes }}</div>
                                        </div>
                                        <div class="status padding" v-show="value.materialStatus === 0">审核中</div>
                                        <div class="status fail" v-show="value.materialStatus === 2">未通过<span
                                                style="color:rgb(148, 147, 147);font-weight:400;word-break: break-all;">（{{
                                                    value.remark }}）</span>
                                        </div>
                                        <div class="status success" v-show="value.materialStatus === 1">已通过</div>
                                        <div class="status remove" v-show="value.materialStatus === 3">已下架</div>
                                    </div>
                                    <div class="handel-list">
                                        <div class="handel remove" v-show="value.materialStatus === 1"
                                            @click="downRemoveHandel(value)"><i class="iconfont icon-remove"></i>下架材料</div>
                                        <div class="handel remove" v-show="value.materialStatus === 3"
                                            @click="downUpHandel(value)"><i class="iconfont icon-upload"></i>上架材料</div>
                                        <div class="handel edit"
                                            v-show="value.materialStatus === 1 || value.materialStatus === 2"
                                            @click="editWorkHandel(value)"><i class="iconfont icon-edit"></i>编辑材料</div>
                                        <div class="handel del" v-show="value.materialStatus != 0"
                                            @click="deleteWorkHandel(value)">
                                            <i class="iconfont icon-delete"></i>删除材料
                                        </div>
                                        <div class="handel setTop"
                                            v-show="value.materialStatus === 1 && value.isTop === false"
                                            @click="setTopWorkHandel(value)"><i class="iconfont icon-setTop"></i>置顶材料</div>
                                        <div class="handel setTop" v-show="value.isTop === true"
                                            @click="cancelSetTopWorkHandel(value)">
                                            <i class="iconfont icon-cancelTop"></i>取消置顶
                                        </div>
                                        <div class="handel edit" @click="goDetail(value.materialId)">
                                            <i class="iconfont icon-view_detail"></i>查看详情
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="tab-edit-history" v-show="value.materialStatus !== 0">
                                <el-button type="primary" size="small" @click="openDialog(value.updateRecords)"
                                    v-show="value.updateRecords">编辑记录</el-button>
                            </div>
                        </div>
                    </div>
                    <div v-else class="empty-list-box">暂无数据</div>
                </el-tab-pane>
            </el-tabs>
            <pagination style="margin-bottom:60px;margin-top:0px" v-show="total > 0" :total="total"
                v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
                @pagination="getPlatformDataList(currentTab, userInfoList.materialSupplierId)" />
        </div>
        <el-dialog title="编辑记录" v-model="open" width="700px" append-to-body center>
            <el-table :data="historyListData" style="width: 100%">
                <el-table-column prop="updateTime" align="center" :show-overflow-tooltip="true" label="编辑时间" />
                <el-table-column prop="materialStatus" align="center" :show-overflow-tooltip="true" label="状态">
                    <template #default="scope">
                        <dict-tag :options="material_status" :value="scope.row.materialStatus" />
                    </template>
                </el-table-column>
                <el-table-column prop="remark" align="center" :show-overflow-tooltip="true" label="备注" />
                <el-table-column align="center" :show-overflow-tooltip="true" label="操作">
                    <template #default="scope">
                        <el-button link type="default" icon="View" size="small"
                            @click="handelDetail(scope.row)">查看</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancel">关 闭</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { getImgUrl } from '@/api/decor/designer.js'
import { getMaterialAuthentication, getPlatformMaterialListTotal, getPlatformMaterialList, editPlatformMaterial, delPlatformMaterial } from '@/api/decor/materialSupplier.js'
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
const { material_status } = proxy.useDict('material_status');
const activeName = ref('allWork')
const loading = ref(true);
const total = ref(0)
const materialTotal = ref(0)
const currentTab = ref(null)
const adjustSort = ref('materialId&desc')
const open = ref(false)
const historyListData = ref()
const userInfoList = ref({})
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    materialName: null,
})
const tabHeaderList = ref([
    { label: '全部材料', name: 'allWork' },
    { label: '审核中', name: 'padding' },
    { label: '未通过', name: 'fail' },
    { label: '已通过', name: 'success' },
    { label: '已下架', name: 'removal' },
])
const listData = ref([])
// 获取材料商详细信息
const getUserInfo = () => {
    getMaterialAuthentication().then((res) => {
        let materialData = res;
        materialData.profilePictureImg = '';
        let imgUrlPromises = [];
        // 获取头像的异步操作
        if (materialData.avatar) {
            let avatarPromise = getImgUrl(materialData.avatar).then((res) => {
                materialData.profilePictureImg = res.data[0].url;
            });
            imgUrlPromises.push(avatarPromise);
        }
        Promise.all(imgUrlPromises).then(() => {
            userInfoList.value = materialData;
            getPlatformDataList(currentTab.value, res.materialSupplierId)
            getPlatformMaterialListTotal(res.materialSupplierId).then((res) => {
                materialTotal.value = res.data
            })
        });
    })
}
// 获取数据
const getPlatformDataList = (status, materialSupplierId) => {
    let data = {}
    if (status === null) {
        data = {
            ...queryParams.value,
            materialSupplierId: materialSupplierId,
            orderByColumn: adjustSort.value.split('&')[0],
            isAsc: adjustSort.value.split('&')[1]
        }
    } else {
        data = {
            ...queryParams.value,
            materialSupplierId: materialSupplierId,
            materialStatus: status,
            orderByColumn: adjustSort.value.split('&')[0],
            isAsc: adjustSort.value.split('&')[1]
        }
    }
    getPlatformMaterialList(data).then((response) => {

        let WorkPromises = [];
        let data = response.rows.map((v) => {
            return { ...v, coverImageUrl: '' }
        })
        data.forEach((v) => {
            if (v.coverImage) {
                let promise = getImgUrl(v.coverImage).then((res) => {
                    v.coverImageUrl = res.data[0].url;
                });
                WorkPromises.push(promise);
            }
        })
        Promise.all(WorkPromises).then(() => {
            listData.value = data;
            total.value = response.total;
            loading.value = false;
        });
    })
}
// tab栏的切换
const handleTabClick = (tab) => {
    switch (tab.props.name) {
        case 'allWork':
            currentTab.value = null
            break
        case 'padding':
            currentTab.value = 0
            break
        case 'fail':
            currentTab.value = 2
            break
        case "success":
            currentTab.value = 1
            break;
        case 'removal':
            currentTab.value = 3
            break;
        default:
            break;
    }

    getPlatformDataList(currentTab.value, userInfoList.value.materialSupplierId)
}
// 排序
const handleCommand = (command) => {
    adjustSort.value = command
    getPlatformDataList(currentTab.value, userInfoList.value.materialSupplierId)
}
// 搜索按钮操作
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getPlatformDataList(currentTab.value, userInfoList.value.materialSupplierId);
}
const clear = () => {
    queryParams.value.materialName = null
    getPlatformDataList(currentTab.value, userInfoList.value.materialSupplierId);
}
// 下架材料
const downRemoveHandel = (value) => {
    const data = {
        materialId: value.materialId,
        materialStatus: 3,
        isTop: value.isTop,
        version: value.version
    }
    proxy.$modal.confirm('是否确认下架材料："' + value.materialName + '"？').then(function () {
        return editPlatformMaterial(JSON.stringify(data));
    }).then(() => {
        getPlatformDataList(currentTab.value, userInfoList.value.materialSupplierId);
        proxy.$modal.msgSuccess("下架成功");
    }).catch(() => { });
}
// 上架材料
const downUpHandel = (value) => {
    const data = {
        materialId: value.materialId,
        materialStatus: 1,
        isTop: value.isTop,
        version: value.version
    }
    proxy.$modal.confirm('是否确认上架材料："' + value.materialName + '"？').then(function () {
        return editPlatformMaterial(JSON.stringify(data));
    }).then(() => {
        getPlatformDataList(currentTab.value, userInfoList.value.materialSupplierId);
        proxy.$modal.msgSuccess("上架成功");
    }).catch(() => { });
}
// 编辑材料
const editWorkHandel = (value) => {
    let updateRecords = value.updateRecords ? value.updateRecords : []
    if (updateRecords.length != 0 && updateRecords[0].materialStatus === 0) {
        proxy.$modal.msgError('请等待管理员审核后再进行修改')
    } else {
        router.push('/materialCom/editMaterialInfo/' + value.materialId)
    }
}
// 置顶
const setTopWorkHandel = (value) => {
    const data = {
        materialId: value.materialId,
        materialStatus: value.materialStatus,
        isTop: true,
        version: value.version
    }
    proxy.$modal.confirm('是否确认置顶材料："' + value.materialName + '"？').then(function () {
        return editPlatformMaterial(JSON.stringify(data));
    }).then(() => {
        getPlatformDataList(currentTab.value, userInfoList.value.materialSupplierId);
        proxy.$modal.msgSuccess("置顶成功");
    }).catch(() => { });
}
// 取消置顶
const cancelSetTopWorkHandel = (value) => {
    const data = {
        materialId: value.materialId,
        materialStatus: value.materialStatus,
        isTop: false,
        version: value.version
    }
    proxy.$modal.confirm('是否确认取消置顶材料："' + value.materialName + '"？').then(function () {
        return editPlatformMaterial(JSON.stringify(data));
    }).then(() => {
        getPlatformDataList(currentTab.value, userInfoList.value.materialSupplierId);
        proxy.$modal.msgSuccess("取消成功");
    }).catch(() => { });
}
// 删除材料
const deleteWorkHandel = (value) => {
    proxy.$modal.confirm('是否确认删除材料："' + value.materialName + '"？').then(function () {
        return delPlatformMaterial(value.materialId);
    }).then(() => {
        proxy.$modal.msgSuccess("删除成功");
        getPlatformDataList(currentTab.value, userInfoList.value.materialSupplierId);
    }).catch(() => { });
}
// 编辑记录
const openDialog = (value) => {
    open.value = true
    historyListData.value = value

}
const cancel = () => {
    open.value = false
}
// 查看
const handelDetail = (value) => {
    router.push('/materialCom/materialDetailInfo/' + value.materialId)
}
// 跳转至详情页面
const goDetail = (materialId) => {
    router.push('/materialCom/materialDetail/' + materialId)
}
getUserInfo()
</script>
<style lang="scss" scoped>
::v-deep(.el-tag.el-tag--info) {
    background: #F0F2F4;
    border-radius: 4px;
    font-family: NotoSansHans, NotoSansHans;
    font-weight: 400;
    font-size: 12px;
    color: #5D5D5D;
    line-height: 18px;
    font-style: normal;
    padding: 8px 12px;
}

:deep(.el-dropdown) {
    border: 1px solid #E1E6ED;
    text-align: center;
    line-height: 36px;
    border-radius: 8px;
    margin-left: 10px;
    padding: 0 10px;
}

:deep(.el-dropdown-menu__item) {
    padding: 6px 24px;
    text-align: left;

    .adjust-sort {
        color: #F28472;
    }
}

:deep(.el-button--primary) {
    background: #eef0f8;
    color: #343333;
}
</style>